import React, {useState, useRef} from 'react'
import {
	Button,
	Space,
	message,
	Popconfirm as Reconfirm,
	Modal,
	InputNumber,
} from 'antd'

import {connect, useDispatch} from 'umi'

import type {
	ActionType,
	EditableFormInstance,
	ProColumns,
} from '@ant-design/pro-components'
import {EditableProTable} from '@ant-design/pro-components'

import moment from 'moment'
import styles from './index.less'
// 可编辑表格
import {integerPattern, twoDecimalPattern} from '@/utils/common/validator'
import DriverRelationView from '../DriverRelationView'
import ChannelRelationView from '../ChannelRelationView'
import DriverRelation from '../DriverRelation'
import ChannelRelation from '../ChannelRelation'
import DriverRewardRules from '@/pages/merchantCenter/sale/driverRewardRules/add/index'
import ChannelRewardRules from '@/pages/merchantCenter/sale/channelRule/add/index'
import 'moment/locale/zh-cn'

type DataSourceType = {
	title: any
	itemName: string
	id: React.Key
	labels?: {
		key: string
		label: string
	}[]
	state?: string
	children?: DataSourceType[]
}
function OrderTypeOne(props: any) {
	const {
		type,
		onlyCode,
		onlyChannelCode,
		costitemList,
		setCostitemList,
		data,
		otherParams,
		location,
	} = props
	// 可编辑表格
	const actionRef = useRef<ActionType>()
	const editorFormRef = useRef<EditableFormInstance<DataSourceType>>()
	const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([])

	// 弹窗
	const [isChannelRelationView, setIsChannelRelationViewOpen] =
		useState(false)
	const [isDriverRelationView, setIsDriverRelationViewOpen] = useState(false)
	const [isModalDriverOpen, setIsModalDriverOpen] = useState(false)
	const [isModalChannelOpen, setIsModalChannelOpen] = useState(false)
	const [copyList, setCopyList] = useState<any[]>([])
	const [row, setRow] = useState<any>()
	const [editrecord, setEditrecord] = useState<any>()

	// 新增司机奖励
	const [isModalDriverRuleOpen, setIsModalDriverRuleOpen] = useState(false)
	const childRefDriverRule = useRef<any>(null)

	// 新增渠道奖励
	const [isModalChannelRuleOpen, setIsModalChannelRuleOpen] = useState(false)
	const childRefChannelRule = useRef<any>(null)
	const queryType = {
		type: '1',
		onlyCode: onlyChannelCode,
		subjectId: data?.subjectId || '',
		subjectName: otherParams?.subjectName || '',
		affiliatedCompanyId: data?.affiliatedCompanyId || '',
		affiliatedCompany: otherParams?.affiliatedCompany || '',
		provinceId: data?.city ? data?.city[0] : '',
		cityId: data?.city ? data?.city[1] : '',
		rovinceName: otherParams ? otherParams?.provinceName : null,
		cityName: otherParams ? otherParams?.cityName : null,
		brandId: data ? data?.brandId : null,
		brandName: otherParams ? otherParams?.brandInfo : null,
		rentTypeId: data ? data?.rentTypeId : null,
		beginTime: data ? moment(data?.beginTime).format('YYYY-MM-DD') : null,
		endTime: data ? moment(data?.endTime).format('YYYY-MM-DD') : null,
		leaseTerm: row ? row?.leaseTerm : null,
	}
	const dispatch = useDispatch()

	// 获取动态表格数据
	const getCostitemList = (list: any) => {
		const arr = list?.map((item: any) => {
			const i = item
			if (editrecord?.id === i?.id) {
				i.rentDriverVOList = []
				i.rentChannelVOList = []
			}
			return i
		})
		setCostitemList(arr)
	}

	const getFieldsError = (callBackFun: any) => {
		if (!data?.subjectId) {
			message.error('请选择主体名称')
			callBackFun(data?.subjectId)
			return data?.subjectId
		}
		if (!data?.affiliatedCompanyId) {
			message.error('请选择所属公司')
			callBackFun(data?.affiliatedCompanyId)
			return data?.affiliatedCompanyId
		}
		if (!data?.city) {
			message.error('请选择城市名称')
			callBackFun(data?.city)
			return data?.city
		}
		if (!data?.brandId) {
			message.error('请选择品牌/车系/车型')
			callBackFun(data?.brandId)
			return data?.brandId
		}
		if (!data?.rentTypeId) {
			message.error('请选择订单类型')
			callBackFun(data?.rentTypeId)
			return data?.rentTypeId
		}
		if (!data?.beginTime) {
			message.error('请选择开始时间')
			callBackFun(data?.beginTime)
			return data?.beginTime
		}
		if (!data?.endTime) {
			message.error('请选择结束时间')
			callBackFun(data?.endTime)
			return data?.endTime
		}
		callBackFun(true)
		return {}
	}

	// 可编辑表格
	const proColumns: ProColumns<DataSourceType>[] = [
		{
			title: (
				<>
					<span className="required">* </span> 租期
				</>
			),
			dataIndex: 'leaseTerm',
			align: 'center',
			width: 200,
			renderFormItem: () => (
				<InputNumber min={1} max={36} style={{width: '100%'}} />
			),
			formItemProps: {
				rules: [
					{
						required: true,
						pattern: integerPattern,
						message: '输入的租期不正确',
					},
				],
			},
		},
		{
			title: '月租金（新签）调整前',
			dataIndex: 'orginRentAmount',
			align: 'center',
			editable: false,
			width: 200,
			hideInTable: type !== 'copy',
			render: (text: any, records: any) => (
				<span>{records.orginRentAmount || 0}</span>
			),
		},
		{
			title: (
				<>
					<span className="required">* </span>
					<span>
						{type !== 'copy'
							? '月租金（新签）'
							: '月租金（新签）调整后'}
					</span>
				</>
			),
			dataIndex: 'rentAmount',
			align: 'center',
			width: 200,
			formItemProps: {
				rules: [
					{
						required: true,
						pattern: twoDecimalPattern,
						message: '输入的月租金不正确',
					},
					{
						max: 10,
						message: '最长10位',
					},
				],
			},
		},
		{
			title: '月租金（新签）升级降幅',
			dataIndex: 'rangeRentAmount',
			align: 'center',
			width: 200,
			editable: false,
			hideInTable: type !== 'copy',
			render: (text: any, records: any) => (
				<span>
					{Number(records.rentAmount || 0) -
						Number(records.orginRentAmount || 0)}
				</span>
			),
		},
		{
			title: '月租金（续签）调整前',
			dataIndex: 'orginRenewRentAmount',
			align: 'center',
			width: 200,
			editable: false,
			hideInTable: type !== 'copy',
			render: (text: any, records: any) => (
				<span>{records.orginRenewRentAmount || 0}</span>
			),
		},
		{
			title: (
				<>
					<span className="required">* </span>
					<span>
						{type !== 'copy'
							? '月租金（续签）'
							: '月租金（续签）调整后'}
					</span>
				</>
			),
			dataIndex: 'renewRentAmount',
			align: 'center',
			width: 200,
			formItemProps: {
				rules: [
					{
						required: true,
						pattern: twoDecimalPattern,
						message: '输入的月租金不正确',
					},
					{
						max: 10,
						message: '最长10位',
					},
				],
			},
		},
		{
			title: '月租金（新签）升级降幅',
			dataIndex: 'rangeRenewRentAmount',
			align: 'center',
			width: 200,
			editable: false,
			hideInTable: type !== 'copy',
			render: (text: any, records: any) => (
				<span>
					{Number(records.renewRentAmount || 0) -
						Number(records.orginRenewRentAmount || 0)}
				</span>
			),
		},
		{
			title: '关联司机奖励',
			hideInTable: type === 'view' || type === 'process',
			dataIndex: 'rentDriverVOLists',
			align: 'center',
			width: 180,
			editable: false,
			render: (text: any, record: any) => (
				<>
					{type !== 'add' && record?.leaseTerm ? (
						<Button
							type="link"
							size="small"
							onClick={() => {
								setRow(() => record)
								setIsDriverRelationViewOpen(true)
							}}>
							查看
						</Button>
					) : null}
					{type !== 'view' && record?.leaseTerm ? (
						<Button
							type="link"
							size="small"
							onClick={() => {
								getFieldsError((res: any) => {
									if (res) {
										setRow(() => record)
										setIsModalDriverOpen(true)
									}
								})
							}}>
							去关联
						</Button>
					) : (
						'--'
					)}
				</>
			),
		},
		{
			title: '关联渠道奖励',
			dataIndex: 'rentChannelVOLists',
			hideInTable: type === 'view' || type === 'process',
			align: 'center',
			width: 180,
			editable: false,
			render: (text: any, record: any) => (
				<>
					{type !== 'add' && record?.leaseTerm ? (
						<Button
							type="link"
							size="small"
							onClick={() => {
								setRow(() => record)
								setIsChannelRelationViewOpen(true)
							}}>
							查看
						</Button>
					) : null}
					{type !== 'view' && record?.leaseTerm ? (
						<Button
							type="link"
							size="small"
							onClick={() => {
								getFieldsError((res: any) => {
									if (res) {
										setRow(() => record)
										setIsModalChannelOpen(true)
									}
								})
							}}>
							去关联
						</Button>
					) : (
						'--'
					)}
				</>
			),
		},
		{
			title: '操作',
			valueType: 'option',
			align: 'center',
			width: 200,
			fixed: 'right',
			hideInTable: type === 'view' || type === 'process',
			render: (text, record: any, _, action) => [
				<Button
					type="link"
					key="editable"
					size="small"
					onClick={() => {
						setEditrecord(() => record)
						action?.startEditable?.(record.id)
					}}>
					编辑
				</Button>,
				<Reconfirm
					placement="topLeft"
					title="你确定要删除这条数据吗？"
					onConfirm={() => {
						const l = [...costitemList].filter(
							(item: any) => item.id !== record.id,
						)
						setCostitemList(l)
					}}
					okText="确定"
					cancelText="取消">
					<Button type="link" key="delete">
						删除
					</Button>
				</Reconfirm>,
			],
		},
	]
	// 取消
	const onCancelView = () => {
		setIsChannelRelationViewOpen(() => false)
		setIsDriverRelationViewOpen(() => false)
	}

	// 取消
	const onCancel = () => {
		setIsModalDriverOpen(() => false)
		setIsModalChannelOpen(() => false)
	}

	// 确定
	const onSubmit = () => {
		setCostitemList(copyList)
		setIsModalDriverOpen(() => false)
		setIsModalChannelOpen(() => false)
	}
	// 司机奖励关闭弹窗
	const onDriverRuleCancel = () => {
		setIsModalDriverRuleOpen(() => false)
	}

	// 司机奖励弹窗提交
	const onDriverRuleSubmit = () => {
		childRefDriverRule?.current?.onSubmit((res: any) => {
			if (res) {
				setIsModalDriverRuleOpen(() => false)
				setIsModalDriverOpen(() => true)
			}
		})
	}

	// 渠道奖励关闭弹窗
	const onChannelRuleCancel = () => {
		setIsModalChannelRuleOpen(() => false)
	}

	// 渠道奖励弹窗提交
	const onChannelRuleSubmit = () => {
		childRefChannelRule?.current?.onSubmit((res: any) => {
			if (res) {
				setIsModalChannelRuleOpen(() => false)
				setIsModalChannelOpen(() => true)
			}
		})
	}

	return (
		<div className={styles.page}>
			<>
				{type !== 'view' ? (
					<Button
						type="primary"
						ghost
						size="small"
						style={{marginBottom: '12px'}}
						onClick={() => {
							actionRef.current?.addEditRecord?.({
								id: `ID${(Math.random() * 100000000).toFixed(
									0,
								)}`,
							})
						}}>
						新增
					</Button>
				) : (
					''
				)}
				<EditableProTable<DataSourceType>
					bordered
					rowKey="id"
					key="id"
					actionRef={actionRef}
					editableFormRef={editorFormRef}
					maxLength={5}
					scroll={{x: 'max-content', y: 480}}
					// 关闭默认的新建按钮
					recordCreatorProps={false}
					columns={proColumns}
					value={costitemList}
					onChange={(value: any) => getCostitemList(value)}
					editable={{
						editableKeys,
						onSave: async () => true,
						onChange: setEditableRowKeys,
						actionRender: (rows: any, config: any, dom: any) => [
							dom.save,
							dom.cancel,
						],
					}}
				/>
				<Modal
					title="司机奖励详情"
					open={isDriverRelationView}
					onCancel={onCancelView}
					width="60%"
					destroyOnClose
					footer={<></>}>
					<DriverRelationView
						rentDriverVOList={row?.rentDriverVOList}
						callBack={(checkData: any) => {
							const list = costitemList?.map((item: any) => {
								const newObject = item
								if (newObject?.id === row?.id) {
									newObject.rentDriverVOList =
										newObject?.rentDriverVOList?.filter(
											(i: any) => checkData?.id !== i.id,
										)
									setRow(() => newObject)
								}
								return newObject
							})
							setCopyList(list)
						}}
					/>
				</Modal>
				<Modal
					title="渠道奖励详情"
					open={isChannelRelationView}
					onCancel={onCancelView}
					width="60%"
					destroyOnClose
					footer={<></>}>
					<ChannelRelationView
						channelRelationList={row?.rentChannelVOList}
						callBack={(checkData: any) => {
							const list = costitemList?.map((item: any) => {
								const newObject = item
								if (newObject?.id === row?.id) {
									newObject.rentChannelVOList =
										newObject?.rentChannelVOList?.filter(
											(i: any) => checkData?.id !== i.id,
										)
									setRow(() => newObject)
								}
								return item
							})
							setCopyList(() => list)
						}}
					/>
				</Modal>

				<Modal
					title={
						<div>
							<Space size={12}>
								<div>司机奖励选择</div>
								<Button
									type="primary"
									size="small"
									onClick={() => {
										const param = {
											subjectId: data?.subjectId,
											affiliatedCompanyId:
												data?.affiliatedCompanyId,
											subjectName:
												otherParams?.subjectName,
											orgName:
												otherParams?.affiliatedCompany,
											city: data?.city,
											provinceName:
												otherParams?.provinceName,
											cityName: otherParams.cityName,
											brandId: data?.brandId,
											rentTypeId: data?.rentTypeId,
											beginTime: moment(
												data?.beginTime,
											).format('YYYY-MM-DD'),
											endTime: moment(
												data?.endTime,
											).format('YYYY-MM-DD'),
											leaseTerm: row?.leaseTerm,
										}

										dispatch({
											type: 'driverRewardRules/updateState',
											payload: {
												ruleParamsPlan: param,
											},
										})
										setIsModalDriverOpen(false)
										setIsModalDriverRuleOpen(true)
									}}>
									新增司机奖励
								</Button>
							</Space>
						</div>
					}
					open={isModalDriverOpen}
					onCancel={onCancel}
					width="60%"
					destroyOnClose
					footer={
						<>
							<Button size="small" onClick={onCancel}>
								取消
							</Button>
							<Button
								type="primary"
								size="small"
								onClick={onSubmit}>
								确定
							</Button>
						</>
					}>
					<DriverRelation
						type="driver"
						data={data}
						onlyCode={onlyCode}
						row={row}
						otherParams={otherParams}
						callBack={(checkData: any) => {
							if (checkData) {
								const list = costitemList?.map((item: any) => {
									const newObject = item
									if (newObject?.id === row?.id) {
										newObject.rentDriverVOList = [
											...checkData,
										]
									}
									return item
								})
								setCopyList(() => list)
							}
						}}
					/>
				</Modal>
				<Modal
					title={
						<div>
							<Space size={12}>
								<div>渠道奖励选择</div>
								<Button
									type="primary"
									size="small"
									onClick={() => {
										setIsModalChannelOpen(false)
										setIsModalChannelRuleOpen(true)
									}}>
									新增渠道奖励
								</Button>
							</Space>
						</div>
					}
					open={isModalChannelOpen}
					onCancel={onCancel}
					width="60%"
					destroyOnClose
					footer={
						<>
							<Button size="small" onClick={onCancel}>
								取消
							</Button>
							<Button
								type="primary"
								size="small"
								onClick={onSubmit}>
								确定
							</Button>
						</>
					}>
					<ChannelRelation
						type="channel"
						onlyCode={onlyChannelCode}
						data={data}
						row={row}
						callBack={(checkData: any) => {
							if (checkData) {
								const list = costitemList?.map((item: any) => {
									const newObject = item
									if (newObject?.id === row?.id) {
										newObject.rentChannelVOList = [
											...checkData,
										]
									}
									return item
								})
								setCopyList(() => list)
							}
						}}
					/>
				</Modal>

				<Modal
					title="新增司机奖励"
					open={isModalDriverRuleOpen}
					onCancel={onDriverRuleCancel}
					width="60%"
					destroyOnClose
					footer={
						<>
							<Button size="small" onClick={onDriverRuleCancel}>
								取消
							</Button>
							<Button
								type="primary"
								size="small"
								onClick={onDriverRuleSubmit}>
								保存
							</Button>
						</>
					}>
					<DriverRewardRules
						cRef={childRefDriverRule}
						location={location}
						queryType={{
							pageType: 'add',
							type: '1',
							onlyCode,
						}}
					/>
				</Modal>

				<Modal
					title="新增渠道奖励"
					open={isModalChannelRuleOpen}
					onCancel={onChannelRuleCancel}
					width="60%"
					destroyOnClose
					footer={
						<>
							<Button size="small" onClick={onChannelRuleCancel}>
								取消
							</Button>
							<Button
								type="primary"
								size="small"
								onClick={onChannelRuleSubmit}>
								保存
							</Button>
						</>
					}>
					<ChannelRewardRules
						cRef={childRefChannelRule}
						location={location}
						queryType={queryType}
					/>
				</Modal>
			</>
		</div>
	)
}

export default connect(({user, driverRewardRules}: any) => ({
	user,
	driverRewardRules,
}))(OrderTypeOne)
